<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
# DB template.
#
# This defines all the configurable parameters and other objects that are needed to run the couchbase service. This template can even be
# saved in OpenShift namespace as well so that have the flexibility to do any project specific customizations. Pls note wherever
# displayName says *** PLEASE DO NOT CHANGE THIS ***, don't touch that as those parameters will be referenced in other places.
#
# Replication mode is not tested yet.
#
# TODO - Later to be updated to statefulset
apiVersion: <%= KUBERNETES_CORE_API_VERSION  %>
kind: Template
metadata:
  name: <%= app.baseName.toLowerCase() %>-couchbase-template
  namespace: <%= openshiftNamespace %>
  annotations:
    description: This template defines objects that are required to spin up a couchbase pod
    tags: db, <%= app.baseName.toLowerCase() %>-couchbase<% if (storageType === 'persistent') { %> ,persistent <% } %> <% if (storageType === 'ephemeral') { %> ,ephemeral <% } %>
    openshift.io/display-name: <%= app.baseName.toLowerCase() %>-couchbase-template
    openshift.io/long-description: >-
        This template provides objects that are required to spin up a couchbase pod. <% if (storageType ==
        'persistent') { %>The database is stored on persistent storage, so any restart of the service will not cause any impact to the data.
        Please make sure you have provisioned PVs (Persistent Volumes) before using this template. <% } %>
        <% if (storageType === 'ephemeral') { %>The database is not stored on persistent storage, so any restart of the service will result in all data being lost.<% } %>
    openshift.io/provider-display-name: JHipster-OpenShift
labels:
  app: <%= app.baseName.toLowerCase() %>-couchbase
  createdBy: JHipster-Team
parameters:
  -
    name: APPLICATION_NAME
    value: <%= app.baseName.toLowerCase() %>-couchbase
    description: Name of the application
    required: true
    displayName: Application Name
  -
    name: SECRET_REF
    value: ds-secret-ref
    description: Name of the secret reference
    required: true
    displayName: "*** PLEASE DO NOT CHANGE THIS ***"
  -
    name: DATABASE_NAME
    displayName: Couchbase Database Name
    description: Name of the Couchbase database accessed
    value: <%= app.baseName.toLowerCase() %>
    required: true
  -
    name: COUCHBASE_ADMIN_USER
    displayName: Couchbase Connection Username
    description: Username for couchbase admin user
    generate: expression
    from: user[A-Z0-9]{3}
    required: true
  -
    name: COUCHBASE_ADMIN_PASSWORD
    displayName: Couchbase Connection Password
    description: Password for the couchbase admin user
    generate: expression
    from: "[a-zA-Z0-9]{16}"
    required: true
  -
    name: VOLUME_CAPACITY
    displayName: Volume Capacity
    description: Volume space available for data, e.g. 512Mi, 2Gi
    value: 1Gi
    required: true
objects:
  -
    apiVersion: <%= KUBERNETES_CORE_API_VERSION  %>
    kind: Secret
    metadata:
      name: ${SECRET_REF}
    stringData:
      database-admin-user: "${COUCHBASE_ADMIN_USER}"
      database-admin-password: "${COUCHBASE_ADMIN_PASSWORD}"
<%_ if (storageType === 'persistent') { _%>
  -
    apiVersion: <%= KUBERNETES_CORE_API_VERSION  %>
    kind: PersistentVolumeClaim
    metadata:
      name: ${APPLICATION_NAME}
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: "${VOLUME_CAPACITY}"
<%_ } _%>
  -
    apiVersion: <%= KUBERNETES_CORE_API_VERSION  %>
    kind: DeploymentConfig
    metadata:
      name: ${APPLICATION_NAME}
      labels:
        app: ${APPLICATION_NAME}
    spec:
      strategy:
        type: Rolling
        rollingParams:
          updatePeriodSeconds: 1
          intervalSeconds: 1
          timeoutSeconds: 600
          maxUnavailable: 25%
          maxSurge: 25%
          post:
            failurePolicy: ignore
            execNewPod:
              command:
                - "/bin/sh"
                - "-ec"
                - |
                    set -x
                    echo "waiting for http://${APPLICATION_NAME}:8091/ui/index.html"
                    while [ "$(curl -Isw '%{http_code}' -o /dev/null http://${APPLICATION_NAME}:8091/ui/index.html#/)" != 200 ]
                    do
                        sleep 5
                    done

                    echo "Setup index and memory quota"
                    curl -X POST http://${APPLICATION_NAME}:8091/pools/default -d memoryQuota=300 -d indexMemoryQuota=300

                    echo "Setup services"
                    curl http://${APPLICATION_NAME}:8091/node/controller/setupServices -d services=kv%2Cn1ql%2Cindex

                    echo "Setup credentials"
                    curl http://${APPLICATION_NAME}:8091/settings/web -d port=8091 -d username=${COUCHBASE_ADMIN_USER} -d password=${COUCHBASE_ADMIN_PASSWORD}

                    echo "Setup Memory Optimized Indexes"
                    curl -u ${COUCHBASE_ADMIN_USER}:${COUCHBASE_ADMIN_PASSWORD} -X POST http://${APPLICATION_NAME}:8091/settings/indexes -d 'storageMode=memory_optimized'

                    echo "Setup bucket $BUCKET"
                    curl -u ${COUCHBASE_ADMIN_USER}:${COUCHBASE_ADMIN_PASSWORD} -X POST http://${APPLICATION_NAME}:8091/pools/default/buckets -d name=${BUCKET} -d bucketType=couchbase -d ramQuotaMB=300 -dauthType=sasl

                    echo "Setup bucket $BUCKET admin user"
                    curl -u ${COUCHBASE_ADMIN_USER}:${COUCHBASE_ADMIN_PASSWORD} -X PUT http://127.0.0.1:8091/settings/rbac/users/local/$BUCKET -d name=$BUCKET -d password=${COUCHBASE_ADMIN_PASSWORD} -d roles="bucket_admin[$BUCKET],bucket_full_access[$BUCKET]"

              containerName: ${APPLICATION_NAME}

        resources:
      triggers:
        -
          type: ConfigChange
      replicas: 1
      selector:
        app: ${APPLICATION_NAME}
      template:
        metadata:
          labels:
            app: ${APPLICATION_NAME}
        spec:
          volumes:
          - name: ${APPLICATION_NAME}-data
            <%_ if (storageType === 'persistent') { _%>
            persistentVolumeClaim:
              claimName: ${APPLICATION_NAME}
            <%_ } _%>
            <%_ if (storageType === 'ephemeral') { _%>
            emptyDir: {}
            <%_ } _%>
          containers:
          - name: ${APPLICATION_NAME}
            image: <%= DOCKER_COUCHBASE %>
            env:
            - name: BUCKET
              value: <%= app.baseName.toLowerCase() %>
            - name: COUCHBASE_DATABASE
              value: ${DATABASE_NAME}
            - name: COUCHBASE_ADMIN_USER
              valueFrom:
                secretKeyRef:
                  name: ${SECRET_REF}
                  key: database-admin-user
            - name: COUCHBASE_ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: ${SECRET_REF}
                  key: database-admin-password
            ports:
            - containerPort: 8091
              protocol: TCP
            - containerPort: 8092
              protocol: TCP
            - containerPort: 8093
              protocol: TCP
            - containerPort: 11210
              protocol: TCP
            command:
                - "/bin/bash"
                - "-ec"
                - |
                    set -x
                    /entrypoint.sh couchbase-server
            readinessProbe:
              timeoutSeconds: 1
              initialDelaySeconds: 15
              httpGet:
                path: /ui/index.html
                port: 8091
                scheme: HTTP
            livenessProbe:
              timeoutSeconds: 1
              initialDelaySeconds: 30
              httpGet:
                path: /ui/index.html
                port: 8091
                scheme: HTTP
            volumeMounts:
            - name: ${APPLICATION_NAME}-data
              mountPath: /opt/couchbase/var/lib/couchbase/data/
            resources:
            imagePullPolicy: IfNotPresent
          restartPolicy: Always
          terminationGracePeriodSeconds: 30
  -
    apiVersion: <%= KUBERNETES_CORE_API_VERSION  %>
    kind: Service
    metadata:
      name: ${APPLICATION_NAME}
      labels:
        app: ${APPLICATION_NAME}
    spec:
      ports:
        -
          name: couchbase-8091
          protocol: TCP
          port: 8091
          targetPort: 8091
        -
          name: couchbase-8092
          protocol: TCP
          port: 8092
          targetPort: 8092
        -
          name: couchbase-8093
          protocol: TCP
          port: 8093
          targetPort: 8093
        -
          name: couchbase-11210
          protocol: TCP
          port: 11210
          targetPort: 11210
      selector:
        app: ${APPLICATION_NAME}
